<template>
  <div v-loading="loading" element-loading-text="初始化中..">
    <textarea :id="name" style="width: 100%; height: 300px">
    </textarea>

    <k-dialog-upload v-model="showUploadImage" multiple @success="onAddImage"/>
  </div>
</template>

<script>
import loadjs from '@/plugin/loadjs'
import KDialogUpload from '@/components/dialog-upload/index'
export default {
  name: 'KEditor',
  components: { KDialogUpload },
  props: {
    value: String,
    name: {
      type: String,
      default: 'ke-editor'
    },
    toolbar: {
      type: Array,
      default: () => {
        return [
          'backcolor forecolor formatselect fontselect fontsizeselect',
          'bold italic underline strikethrough alignleft aligncenter alignright alignjustify alignnone' +
          'removeformat subscript hr bullist numlist link unlink table myimage',
        ]
      }
    }
  },
  data () {
    return {
      editor: null,
      showUploadImage: false,
      images: [],
      loading: true,
      inited: false,
    }
  },
  computed: {
    editorid () {
      return 'ke-editor-' + KE.timestamp(true) + '_' + KE.randomNum(1, 1000)
    }
  },
  watch: {
    value (str) {
      if (!this.inited) {
        this.inited = true
        str === this.editor.getContent() || this.editor.setContent(str)
      }
    }
  },
  mounted () {
    this.loading = true
    loadjs(process.env.BASE_URL + 'js/tinymce/tinymce.min.js', 'tinymce')
      .then(() => {
        tinymce.init({
          selector: '#' + this.name,
          language: 'zh_CN',
          height: 301,
          skinUiCss: 'lightgray',
          plugins: 'lists hr link table textcolor',
          menu: [],
          toolbar: this.toolbar,
          setup: (editor) => {
            this.editor = editor
            editor.on('init', (e) => {
              this.loading = false
              if (this.value) {
                editor.setContent(this.value)
              }
            })

            editor.addButton('myimage', {
              title: '上传图片',
              icon: 'image',
              onclick: () => {
                this.showUploadImage = true
              }
            })
          },
          init_instance_callback: (editor) => {
            editor.on('Change', (e) => {
              this.$emit('input', editor.getContent())
            })
          }
        })
      })
  },
  methods: {
    setContent (val) {
      this.editor.setContent(val)
    },
    setFocus () {
      this.editor.setFocus()
    },
    onAddImage (info) {
      info.map((item) => {
        this.editor.insertContent('<img src="' + item['url'] + '"/>')
      })
    }
  },
  destroyed () {
    console.log('销毁')
    this.editor?.destroy()
  }
}
</script>

<style scoped>

</style>
